class Node{//节点
    constructor(element) {
        this.element = element;
        this.next = null;
    }   
}

class YsfList{
    constructor(){
        this.head = null; //首个节点
        this.count = 0; //节点数量
    }
    push(element){//向链表尾部添加⼀个新元素
        let node = new Node(element);
        if(this.head === null){//为空时
            this.head = node;
            node.next = this.head;
        }else{//不为空时
            let last = this.getElementAt(this.count-1);
            last.next = node;
            node.next = this.head;
        }
        this.count++;
    }
    getElementAt(index){//查找指定元素
        let current = this.head;
        for(let i = 0;i < index;i++){
            current = current.next;
        }
        return current
    }
    ysfCircle(sum,num){ //约瑟夫环
        for(let i = 1;i<=sum;i++){//循环向链表中添加元素
            this.push(i);
        }
        let helper = this.head; 
        let current = this.head;
        while(helper.next != this.head){
            helper = helper.next;
        }
        let n=1;//计数器
        while(this.count > 15){//当人数为15人时就停止删除元素节点
            for(let i = 0;i<num-1;i++){
                helper = helper.next;
                current = current.next;
            }
            console.log(`第${n++}跳下水是${current.element}号`)
            helper.next = current.next;
            current = current.next;
            this.count--;
        }
    }
}
let ysf = new YsfList ();
ysf.ysfCircle(30,9)
